<?php
namespace app\reception\classs;
use app\reception\logic\LogLogic;
use think\Db;

class AdvertBehavior
{

    /*记录订单广告数据*/
    public function writeOrderRecord($orderData,$oid)
    {

        $record = Db::table('quick_user_behavior_monitoring')
                ->where('channel_id',$orderData['channel_id'])
                ->where('uid',$orderData['uid'])
                ->where('link_id',$orderData['link_id'])
                ->where('type',$orderData['advert_media_id'])
                ->field('id,advertiser_id,campaign_id,aid,cid')->order('id DESC')->findOrEmpty();

        if ($record && strlen($record['advertiser_id']) > 1) {
            $data['order_id']       = $oid;
            /*$data['uid']            = $orderData['uid'];
            $data['reg_date']       = $orderData['user_reg_date'];
            $data['channel_id']     = $orderData['channel_id'];
            $data['total_fee']      = $orderData['total_fee'];
            $data['quick_id']       = $orderData['quick_id'];*/
            $data['behavior_id']    = $record['id'];
            $data['adtype']         = $orderData['advert_media_id'];
            $data['advertiser_id']  = $record['advertiser_id'];
            $data['aid']            = $record['aid'];
            $data['cid']            = $record['cid'];
            $data['campaign_id']    = $record['campaign_id'];
            $data['create_date']    = $orderData['create_date'];

            Db::table('pay_order_advert')->insert($data);
        }
    }

    /*记录广告行为*/
    public function writeRecord($pageParam,$uid,$channel_id,$link_id)
    {
        $params = json_decode($pageParam,true);
        $params['channel_id'] = $channel_id;

        if( !isset($params['adtype']) )
        {
            return true;
        }

        if($params['adtype'] == 'ks' && $params['callback'] != '__CALLBACK__')
        {
            $this->writeKsRecord($params,$uid,$link_id);
        }

        if($params['adtype'] == 'jlq')
        {
            $this->writeJlqRecord($params,$uid,$link_id);
        }

        if($params['adtype'] == 'jl')
        {
            $this->writeJlRecord($params,$uid,$link_id);
        }

        if($params['adtype'] == 'baidu')
        {
            $this->writeBaiduRecord($params,$uid,$link_id);
        }

        if($params['adtype'] == 'uc')
        {
            $this->writeUcRecord($params,$uid,$link_id);
        }

        if($params['adtype'] == 'vivo')
        {
            $this->writeVivoRecord($params,$uid,$link_id);
        }

        if($params['adtype'] == 'oppo')
        {
            $this->writeOppoRecord($params,$uid,$link_id);
        }

        if($params['adtype'] == 'bilibili')
        {
            $this->writeBilibiliRecord($params,$uid,$link_id);
        }


    }

    /*快手广告行为记录*/
    private function writeKsRecord($pageparams,$uid,$link_id)
    {
        $ip_addr = $this->get_ip();

        //记录快手回调信息参数
        $behavior_data = [
            'ip_addr'       => $ip_addr,
            'link'          => $pageparams['callback'] ?: '',
            'created_at'    => date('Y-m-d H:i:s'),
            'channel_id'    => $pageparams['channel_id'],
            'usersign'      => $uid ?: 0,
            'uid'           => $uid ?: 0,
            'link_id'       => $link_id,
            'type'          => 1,
            'advertiser_id' => (isset($pageparams['adid']) && $pageparams['adid']) ? $pageparams['adid'] : '',
            'campaign_id'   => (isset($pageparams['kaid']) && $pageparams['kaid']) ? $pageparams['kaid'] : '',
            'aid'           => (isset($pageparams['kdid']) && $pageparams['kdid']) ? $pageparams['kdid'] : '',
            'cid'           => (isset($pageparams['kcid']) && $pageparams['kcid']) ? $pageparams['kcid'] : '',
            'oaid_md5'      => (isset($pageparams['oaidmd5']) && $pageparams['oaidmd5']) ? $pageparams['oaidmd5'] : ''
        ];
        Db::table('quick_user_behavior_monitoring')->insert($behavior_data);
    }

    /*巨量快应用广告行为记录*/
    private function writeJlqRecord($pageparams,$uid,$link_id)
    {
        if (isset($pageparams['clickid']) && $pageparams['clickid']) {

            $ip_addr = $this->get_ip();

            $cid = '';
            /*if(isset($pageparams['mid1']) && $pageparams['mid1'] != '__MID1__')
            {
                $cid = $pageparams['mid1'];
            }
            if(isset($pageparams['mid2']) && $pageparams['mid2'] != '__MID2__')
            {
                $cid = $pageparams['mid2'];
            }*/
            if(isset($pageparams['mid3']) && $pageparams['mid3'] != '__MID3__')
            {
                $cid = $pageparams['mid3'];
            }
            /*if(isset($pageparams['mid4']) && $pageparams['mid4'] != '__MID4__')
            {
                $cid = $pageparams['mid4'];
            }
            if(isset($pageparams['mid5']) && $pageparams['mid5'] != '__MID5__')
            {
                $cid = $pageparams['mid5'];
            }
            if(isset($pageparams['mid6']) && $pageparams['mid6'] != '__MID6__')
            {
                $cid = $pageparams['mid6'];
            }*/

            $oaid = '';
            if (isset($pageparams['oaid']) && $pageparams['oaid'] && $pageparams['oaid'] != '__OAID__') {
                $oaid = $pageparams['oaid'];
            }
            if (isset($pageparams['oaidmd5']) && $pageparams['oaidmd5'] && $pageparams['oaidmd5'] != '__OAID_MD5__') {
                $oaidmd5 = $pageparams['oaidmd5'];
            } else {
                $oaidmd5 = strlen($oaid) > 1 ? md5($pageparams['oaid']) : '';
            }


            $behavior_data['ip_addr']       = $ip_addr;
            $behavior_data['link']          = json_encode($pageparams);
            $behavior_data['created_at']    = date('Y-m-d H:i:s');
            $behavior_data['channel_id']    = $pageparams['channel_id'];
            $behavior_data['type']          = 2;
            $behavior_data['usersign']      = $uid ?: 0;
            $behavior_data['uid']           = $uid ?: 0;
            $behavior_data['link_id']       = $link_id;
            $behavior_data['advertiser_id'] = (isset($pageparams['adid']) && $pageparams['adid']) ? $pageparams['adid'] : '';
            //1.0广告组ID 2.0项目ID
            $behavior_data['campaign_id']   = (isset($pageparams['campaign_id']) && $pageparams['campaign_id']) ? $pageparams['campaign_id'] : '';
            $behavior_data['aid']           = (isset($pageparams['aid']) && $pageparams['aid']) ? $pageparams['aid'] : '';
            $behavior_data['cid']           = $cid; //2.0素材ID
            //$behavior_data['cid']           = (isset($pageparams['cid']) && $pageparams['cid']) ? $pageparams['cid'] : ''; //1.0创意ID
            $behavior_data['oaid_md5']      = $oaidmd5;

            Db::table('quick_user_behavior_monitoring')->insertGetId($behavior_data);
        }
    }

    /*巨量二跳广告行为记录*/
    private function writeJlRecord($pageparams,$uid,$link_id)
    {
//        LogLogic::addLog('2t-r',json_encode($pageparams));
        if ((isset($pageparams['request_id']) && $pageparams['request_id']) || (isset($pageparams['req_id']) && $pageparams['req_id'])) {
            //很奇怪，有时候会自动携带req_id，然后request_id值为__REQUEST_ID__，这种是少数情况，但还是要优先使用req_id
            if (isset($pageparams['req_id']) && $pageparams['req_id'] != '' && $pageparams['req_id'] != '__REQUEST_ID__'){
                $usersign = strval($pageparams['req_id']);
            }else{
                $usersign = strval($pageparams['request_id']);
            }
            if ($usersign && $usersign != '__REQUEST_ID__') {
                $jlWhere = [
                    'channel_id' => $pageparams['channel_id'],
                    'type' => 3,
                    'usersign' => $usersign,
                    'uid' => 0,
                ];
                Db::table('quick_user_behavior_monitoring')->where($jlWhere)->update(['uid' => $uid, 'link_id' => $link_id]);
            }

        }
    }



    /*百度广告行为记录*/
    private function writeBaiduRecord($pageparams, $uid, $link_id)
    {
        //LogLogic::addLog('baidu-r', json_encode($pageparams));
        $usersign = $pageparams['bd_vid'];
        if ($usersign && $usersign != '__BD_VID__') {
            $jlWhere = [
                'channel_id' => $pageparams['channel_id'],
                'type' => 4,
                'usersign' => $usersign,
                'uid' => 0,
            ];
            Db::table('quick_user_behavior_monitoring')->where($jlWhere)->update(['uid' => $uid, 'link_id' => $link_id]);
        }
    }

    /*UC广告行为记录*/
    private function writeUcRecord($pageparams, $uid, $link_id)
    {
        LogLogic::addLog('uc-r', json_encode($pageparams));
        $ip_addr = $this->get_ip();
        $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        if ($ua){
            $usersign = md5(get_phone_brand($ua) . '_' . $ip_addr);
            $jlWhere = [
                'channel_id'    => $pageparams['channel_id'],
                'type'          => 5,
                'usersign'      => $usersign,
                'uid'           => 0,
                'link_id'       => $link_id,
            ];
            Db::table('quick_user_behavior_monitoring')->where($jlWhere)->update(['uid' => $uid]);
        }
    }

    /*vivo广告行为记录*/
    private function writeVivoRecord($pageparams, $uid, $link_id)
    {
//        LogLogic::addLog('vivo-r', json_encode($pageparams));
        if (isset($pageparams['reqId']) && $pageparams['reqId']) {
            $ip = request()->ip();
            $usersign = $pageparams['reqId'];
            $akey = Db::table("quick_ad_account_vivo")->where("mysign", $pageparams['mysign'])->cache(3600)->value('akey');//数据源id
            $data = [];
            $data['ip_addr'] = $ip;
            $data['link'] = json_encode($pageparams, JSON_UNESCAPED_UNICODE);
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['channel_id'] = $pageparams['channel_id'];
            $data['type'] = 6;
            $data['usersign'] = $usersign;
            $data['adsign'] = $pageparams['mysign'];
            $data['advertiser_id'] = $akey ? $akey : '';//广告主id
            $data['campaign_id'] = '';//广告组id
            $data['aid'] = '';//广告计划id
            $data['cid'] = '';//广告创意id
            $data['link_id'] = $link_id;
            $data['uid'] = $uid;
            $data['oaid_md5'] = $pageparams['oaidmd5'] && $pageparams['oaidmd5'] != '__OAIDMD5__' ? $pageparams['oaidmd5'] : '';
            Db::table('quick_user_behavior_monitoring')->insertGetId($data);
        }
    }


    /*oppo广告行为记录*/
    private function writeOppoRecord($pageparams, $uid, $link_id)
    {
        $usersign = $pageparams['req_id'];
        if ($usersign && $usersign != '$req$') {
            $jlWhere = [
                'channel_id' => $pageparams['channel_id'],
                'type' => 7,
                'usersign' => $usersign,
                'uid' => 0,
            ];
            Db::table('quick_user_behavior_monitoring')->where($jlWhere)->update(['uid' => $uid, 'link_id' => $link_id]);
        }
    }

    /*Bilibili广告行为记录*/
    private function writeBilibiliRecord($pageparams, $uid, $link_id)
    {
        LogLogic::addLog('bilibili_r', json_encode($pageparams));

        $ip_addr = $this->get_ip();
        $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        if ($ua){
            $usersign = md5(get_phone_brand($ua) . '_' . $ip_addr);
            $jlWhere = [
                'channel_id'    => $pageparams['channel_id'],
                'type'          => 8,
                'usersign'      => $usersign,
                'uid'           => 0,
                'link_id'       => $link_id,
            ];
            Db::table('quick_user_behavior_monitoring')->where($jlWhere)->update(['uid' => $uid]);
        }
    }


    private function get_ip()
    {
        //判断服务器是否允许$_SERVER
        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            } else {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
        } else {
            //不允许就使用getenv获取
            if (getenv("HTTP_X_FORWARDED_FOR")) {
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            } elseif (getenv("HTTP_CLIENT_IP")) {
                $realip = getenv("HTTP_CLIENT_IP");
            } else {
                $realip = getenv("REMOTE_ADDR");
            }
        }
        return $realip;
    }

}